<template>
    <div class="l-box">
        <div class="dbox">
            <div class="box">
                <h1>管理员登录</h1>
                <div>
                    <input type="text" v-model="user.account" placeholder="请输入账号">
                </div>
                <div>
                    <input type="password" v-model="user.password" placeholder="请输入密码">
                </div>
                <div class="code">
                    <input type="text" v-model="user.captcha" placeholder="请输入验证码">
                    <canvas ref="canvas" @click="getVerify"></canvas>
                </div>
                <div>
                    <button @click="signinFn">登录</button>
                </div>
            </div>
        </div>
        
    </div>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { onMounted, ref } from 'vue';
import api from '../api/index';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { sigin, test } from '../api/request'
import {useRouter} from 'vue-router'

const canvas = ref<HTMLCanvasElement | null>(null);
const w: number = 100;
const h: number = 40;
const host = api.url;
let pen: CanvasRenderingContext2D | null = null;

// 定义用户类型
type U = {
    account: string,
    password: string,
    captcha: string
};

const user = ref<U>({
    account: "",
    password: "",
    captcha: ""
});

const router = useRouter()
const signinFn = async () => {


    const { account, password, captcha } = user.value;
    if (account && password && captcha) {
        let isShow = false; 
        try {
            const content = await test({ captcha }); // 直接使用 await
            if (content.code === 200) {
                isShow = true;
            } else {
                ElMessage({
                    type: 'error',
                    message: content.msg
                });
            }
        } catch (error) {
            console.error('请求失败:', error); // 捕获并处理任何错误
            ElMessage.error('请求失败，请重试！');
        }

        if (isShow) {
            try {
                const content = await sigin({ account, password, role: 1 });
                if (content) {
                    const { code, msg } = content;
                    if (code === 200) {
                        const { token} = content
                        // localStorage.setItem('NICKNAME',nickName)
                        localStorage.setItem('TOKEN', token)
                        ElMessage({
                            type:'success',
                            message: content.msg
                        })
                        setTimeout(() => {
                            router.replace({ path: '/' });
                        }, 150);

                    } else {
                        ElMessage({
                            type: 'error',
                            message: msg
                        });
                    }
                } else {
                    ElMessage.error('登录请求返回无效数据。');
                }
            } catch (error) {
                console.error('登录请求失败:', error);
                ElMessage.error('登录请求失败，请重试！');
            }
        }
    } else {
        ElMessage.error('输入框不能为空！');
    }
};

onMounted(() => {
    const ele = canvas.value;
    const img = new Image();
    img.src = `${host}/api/ver/captcha`;

    if (ele) {
        ele.width = w;
        ele.height = h;
        pen = ele.getContext('2d');
        if (pen) {
            img.onload = () => {
                pen.drawImage(img, 0, 0, w, h);
            };

            img.onerror = () => {
                console.error('图像加载失败');
            };
        }
    }
});

// 获取验证码的函数
const getVerify = () => {
    if (!pen) {
        console.error('上下文未定义');
        return;
    }

    const img = new Image();
    img.src = `${host}/api/ver/captcha?${Math.random()}`;
    pen.clearRect(0, 0, w, h);

    img.onload = () => {
        pen.drawImage(img, 0, 0, w, h);
    };

    img.onerror = () => {
        console.error('图像加载失败');
    };
};
</script>

<style scoped lang="scss">
@import '../common/scss/variable.scss';
.l-box {
    width: 100vw;
    height: 100vh;
    background-repeat: no-repeat;
    background-size: cover;
    background-image: url(../assets/img/bg1.webp);
    overflow: hidden;
}

.dbox {
    width: 400px;
    height: 360px;
    margin: 200px auto 0;
    background-color: #fff;

    .box {
        width: 343px;
        height: 100%;
        margin: 0 auto;

        h1 {
            padding-top: 20px;
            font-size: 36px;
            text-align: center;
        }

        >div {
            width: 100%;

            >input,
            button {
                width: 100%;
                height: 52px;
                margin-top: 10px;
                padding-left: 20px;
                box-sizing: border-box;
                border-radius: 10px;
            }

            button {
                border: 0;
                background-color: #3498db;
                color: #fff;
                font-size: 16px;
                cursor: pointer;
            }
        }

        .code {
            position: relative;

            /* 使 canvas 相对于这个 div 定位 */
            input {
                position: relative;
                /* 确保输入框正常显示 */
                z-index: 1;
                /* 确保输入框在 canvas 之上 */
            }

            canvas {
                position: absolute;
                /* 绝对定位 */
                top: 16px;
                /* 与输入框对齐 */
                right: 10px;
                /* 设置与右边的间距 */
                z-index: 22;
                /* 确保 canvas 在输入框下方 */
            }
        }
    }
}
</style>